package com.leyou.upload.service;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
public class UploadService {
    //打印日志
    private static final Logger logger= LoggerFactory.getLogger(UploadService.class);
    //图片后缀名组成的集合
    private static final List<String> suffixes= Arrays.asList("image/png","image/jpg","image/jpeg","image/gif");

    @Autowired
    private FastFileStorageClient storageClient;
    //上传图片
    public String upload(MultipartFile image) throws IOException {
        try {
            //图片信息校验
            //判断是否是规定的后缀名
            String type = image.getContentType();
            if(!suffixes.contains(type)){
                logger.debug("上传失败 不是以规定的后缀名结尾的 {}"+type);
                return null;
            }

            //校验文件内容
            BufferedImage read = ImageIO.read(image.getInputStream());
            if(read==null){
                logger.debug("文件内容不符合要求");
                return null;
            }

            //上传到fastDFS上
            //获取文件后缀名
            String extension= StringUtils.substringAfterLast(image.getOriginalFilename(),".");
            StorePath storePath = storageClient.uploadFile(image.getInputStream(), image.getSize(), extension, null);
            //返回文件路径
            return "http://image.leyou.com/"+storePath.getFullPath();
           /* //上传图片
            //生成文件上传的目录
            File file = new File("D://syg/imaxwge");
            if(!file.exists()){
                file.mkdirs();
            }
            //保存图片
            image.transferTo(new File(file,image.getOriginalFilename()));
            return "http://localhost:1000/"+image.getOriginalFilename();
*/
        }catch (Exception e){
            return null;
        }
    }

}
